<template>
  <div class="wechat-callback">
    <el-container class="layout-container">
      <!-- 头部 -->
      <el-header class="app-header">
        <div class="header-content">
          <h1 class="header-title">微信授权处理</h1>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main class="app-main">
        <div class="main-container">
          <WechatAuth @auth-success="handleAuthSuccess" @auth-error="handleAuthError" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import WechatAuth from '~/components/WechatAuth.vue'
import { ElMessage } from 'element-plus'

// 处理微信授权成功
const handleAuthSuccess = (data: any) => {
  console.log('微信授权成功，准备跳转到访客登记页面:', data)

  // 保存微信用户信息到sessionStorage
  if (process.client) {
    sessionStorage.setItem('wechatUserInfo', JSON.stringify(data))
  }

  // 跳转到访客登记页面，携带必要的参数
  const router = useRouter()
  const route = useRoute()
  const qybh = route.query.qybh as string || '65ad7a5723244a13a1703c134b1bb627'
  const qymc = route.query.qymc as string || '相城光辉芯片制造有限公司'

  router.push({
    path: '/visitor-register',
    query: {
      QYBH: qybh,
      QYMC: qymc,
      WXID: data.openid,
      fromWechat: 'true'
    }
  })
}

// 处理微信授权失败
const handleAuthError = (error: string) => {
  console.error('微信授权失败:', error)
  ElMessage.error(`微信授权失败: ${error}`)

  // 3秒后跳转回首页
  const router = useRouter()
  const route = useRoute()
  const qybh = route.query.qybh as string
  const qymc = route.query.qymc as string
  setTimeout(() => {
    router.push({
      path: '/visitor-register',
      query: {
        QYBH: qybh,
        QYMC: qymc
      }
    })
  }, 3000)
}
</script>

<style scoped>
.wechat-callback {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.layout-container {
  min-height: 100vh;
}

.app-header {
  background: transparent;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 2rem 0;
}

.header-content {
  text-align: center;
}

.header-title {
  font-size: 2.5rem;
  margin-bottom: 0.5rem;
  font-weight: 300;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.app-main {
  padding: 2rem 0;
  background: #f5f7fa;
}

.main-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-container {
    padding: 0 15px;
  }

  .header-title {
    font-size: 2rem;
  }
}
</style>
